package com.masterclient.app.modules.shop;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselibrary.bean.shop.DealerStoreInfoBean;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.shop.contract.DealerStoreInfoContract;
import com.masterclient.app.modules.shop.contract.DealerStoreInfoPresenter;
import com.masterclient.app.widget.TitlebarView;
import com.masterclient.app.widget.imagepick.PicassoImageLoader;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import top.zibin.luban.Luban;

/**
 * @auther hjian
 * @date 2020/9/11.
 */
@Route(path = AroutePath.DEALER_STORE_INFO_ACTIVITY)
public class DealerStoreInfoActivity extends BaseActivity<DealerStoreInfoPresenter> implements DealerStoreInfoContract.View {

    @BindView(R.id.dealer_store_info_titlebar)
    TitlebarView dealerStoreInfoTitlebar;
    @BindView(R.id.dealer_store_info_default_logo)
    ImageView dealerStoreInfoDefaultLogo;
    @BindView(R.id.dealer_store_info_default_radio)
    ImageView dealerStoreInfoDefaultRadio;
    @BindView(R.id.dealer_store_info_logo)
    ImageView dealerStoreInfoLogo;
    @BindView(R.id.dealer_store_info_logo_update)
    TextView dealerStoreInfoLogoUpdate;
    @BindView(R.id.dealer_store_info_radio)
    ImageView dealerStoreInfoRadio;
    @BindView(R.id.dealer_store_info_name)
    EditText dealerStoreInfoName;
    @BindView(R.id.dealer_store_info_name_desc)
    TextView dealerStoreInfoNameDesc;
    @BindView(R.id.dealer_store_info_address)
    TextView dealerStoreInfoAddress;

    private String logoUrl,defaultLogoUrl;
    private boolean isSelectDefault = true;
    private ProgressLoginDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dealer_store_info);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarDarkFont(true).fitsSystemWindows(true).init();

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(true);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        imagePicker.setFocusWidth(800);
        imagePicker.setFocusHeight(800);

        dealerStoreInfoTitlebar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
                String name = dealerStoreInfoName.getText().toString().trim();
                if (name.length()<2){
                    ToastUtil.showToast("店铺名称在2-15个字以内");
                    return;
                }
                showProgress();
                mPresenter.updateInfo(isSelectDefault?defaultLogoUrl:logoUrl,name,isSelectDefault?"1":"0");
            }
        });

        mPresenter.getStoreInfo();
    }

    private void showProgress(){
        if (progressDialog == null){
            progressDialog = new ProgressLoginDialog(this);
        }
        progressDialog.show();
        progressDialog.setDesc("");
    }

    private void dismissProgres(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }

    @Override
    public void showStoreInfo(DealerStoreInfoBean dataBean) {
        dealerStoreInfoAddress.setText("1".equals(dataBean.getHas_address())?"去查看":"去添加");
        dealerStoreInfoAddress.setTextColor(Color.parseColor("1".equals(
                dataBean.getHas_address())?"#141922":"#999FAA"));
        dealerStoreInfoName.setText(dataBean.getName());
        dealerStoreInfoNameDesc.setText(dataBean.getSample_name());
        logoUrl = dataBean.getLogo();
        defaultLogoUrl = dataBean.getDefault_logo();
        ViewTransformUtil.glideImageView(mContext,defaultLogoUrl,dealerStoreInfoDefaultLogo,
                new Transformation[]{new CenterCrop(), new RoundedCornersTransformation(
                        ScreenUtils.dp2px(7), 0)},R.mipmap.defaults);
        ViewTransformUtil.glideImageView(mContext,logoUrl,dealerStoreInfoLogo,
                new Transformation[]{new CenterCrop(), new RoundedCornersTransformation(
                        ScreenUtils.dp2px(7), 0)},R.mipmap.dealer_bench_setting_avatar_add);
        dealerStoreInfoRadio.setVisibility(TextUtils.isEmpty(logoUrl)?View.GONE:View.VISIBLE);
        switchDefaultLogo(TextUtils.isEmpty(logoUrl));
        dealerStoreInfoLogoUpdate.setVisibility(TextUtils.isEmpty(logoUrl)?View.GONE:View.VISIBLE);
    }

    @Override
    public void uploadImgResult(boolean isSuccess, UploadImgBean.DataBean bean) {
        logoUrl = bean.getSh_image_url();
        ViewTransformUtil.glideImageView(mContext,logoUrl,dealerStoreInfoLogo,
                new Transformation[]{new CenterCrop(), new RoundedCornersTransformation(
                        ScreenUtils.dp2px(7), 0)},R.mipmap.defaults);

        dealerStoreInfoRadio.setVisibility(View.VISIBLE);
        dealerStoreInfoLogoUpdate.setVisibility(View.VISIBLE);
        if (isSelectDefault){
            switchDefaultLogo(false);
        }
    }

    @Override
    public void updateResult(boolean isSuccess) {
        dismissProgres();
        ToastUtil.showToast("店铺设置成功");
        finish();
    }



    @OnClick({R.id.dealer_store_info_default_layout,R.id.dealer_store_info_radio,R.id.dealer_store_info_logo,R.id.dealer_store_info_logo_update, R.id.dealer_store_info_address_layout, })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dealer_store_info_default_layout:
                if (isSelectDefault) return;
                switchDefaultLogo(true);
                break;
            case R.id.dealer_store_info_radio:
                if (!isSelectDefault) return;
                switchDefaultLogo(false);
                break;
            case R.id.dealer_store_info_logo:
            case R.id.dealer_store_info_logo_update:
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, 0x67);
                break;
            case R.id.dealer_store_info_address_layout:
                ARouter.getInstance().build(FCRouterPath.MINE_ADDRESS_PATH).withString("form","dealer").navigation(this,new FCBaseIntercept());
                break;
        }
    }

    private void switchDefaultLogo(boolean isSelect){
        isSelectDefault = isSelect;
        if (isSelectDefault){
            dealerStoreInfoRadio.setImageResource(R.mipmap.dealer_bench_radio_default);
            dealerStoreInfoDefaultRadio.setImageResource(R.mipmap.dealer_bench_radio);
        }else {
            dealerStoreInfoRadio.setImageResource(R.mipmap.dealer_bench_radio);
            dealerStoreInfoDefaultRadio.setImageResource(R.mipmap.dealer_bench_radio_default);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 0x67) {
            List<ImageItem> images = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
           if (images.size()>0){
               Observable.just(new File(images.get(0).path)).map(new Function<File, File>() {
                   @Override
                   public File apply(@NonNull File file) throws Exception {
                       return Luban.with(mContext).load(file).get();
                   }
               }).observeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                   @Override
                   public void accept(@NonNull File file) throws Exception {
                       mPresenter.uploadImage(file);
                   }
               });
           }
        }
    }
}
